package routers

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/zhongshaofa/swan-jobs/internal/controllers"
	"github.com/zhongshaofa/swan-jobs/internal/plugin"
	"github.com/zhongshaofa/swan-jobs/internal/routers/handle"
	"github.com/zhongshaofa/swan-jobs/internal/routers/middleware"
)

// InitRouter initialize routing information
func InitRouter() *gin.Engine {
	router := gin.New()
	router.Use(cors.Default())

	router.Use(middleware.JaegerTrace())
	router.Use(middleware.GinLogger(plugin.Logger))
	router.Use(middleware.GinRecovery(plugin.Logger, true))

	router.NoRoute(handle.NoRouteHandle)
	router.NoMethod(handle.NoMethodHandle)

	// 不需要登录鉴权
	noAuthRouter := router.Group("backend")
	{
		noAuthRouter.POST("login", controllers.Login.Login)
	}

	// 需要登录鉴权
	authRouter := router.Group("backend")
	{
		authRouter.Use(middleware.VerifyAuth())

		// 退出登录
		authRouter.POST("login/out", controllers.Login.Out)

		user := authRouter.Group("user")
		{
			user.Use(middleware.VerifyAllow())
			user.GET("list", controllers.User.List)
			user.POST("add", controllers.User.Add)
			user.POST("edit", controllers.User.Edit)
			user.GET("detail", controllers.User.Detail)
			user.POST("delete", controllers.User.Delete)
			user.POST("reset_password", controllers.User.ResetPassword)
			user.POST("switch_status", controllers.User.SwitchStatus)
			user.GET("application/list", controllers.User.ApplicationList)
			user.POST("application/auth", controllers.User.ApplicationAuth)
		}

		client := authRouter.Group("client")
		{
			client.Use(middleware.VerifyAllow())
			client.GET("list", controllers.Client.List)
			client.POST("add", controllers.Client.Add)
			client.POST("edit", controllers.Client.Edit)
			client.GET("detail", controllers.Client.Detail)
			client.POST("delete", controllers.Client.Delete)
			client.POST("switch_status", controllers.Client.SwitchStatus)
		}

		application := authRouter.Group("application")
		{
			application.GET("list", controllers.Application.List)
			application.POST("add", controllers.Application.Add)
			application.POST("edit", controllers.Application.Edit)
			application.GET("detail", controllers.Application.Detail)
			application.POST("delete", controllers.Application.Delete)
			application.POST("switch_status", controllers.Application.SwitchStatus)
			application.GET("client/list", controllers.Application.ClientList)
			application.POST("client/auth", controllers.Application.ClientAuth)
		}

		task := authRouter.Group("task")
		{
			task.GET("list", controllers.Task.List)
			task.POST("add", controllers.Task.Add)
			task.POST("edit", controllers.Task.Edit)
			task.GET("detail", controllers.Task.Detail)
			task.POST("delete", controllers.Task.Delete)
			task.POST("switch_status", controllers.Task.SwitchStatus)
			task.GET("exec_time/list", controllers.Task.ExecTimeList)
		}

	}

	return router
}
